/**
 * zy
 */
class DB {
	constructor(tableName, dbName) {
		this.name = tableName;
		this.path = '_doc/' + dbName;
		this.openDB();
	}
	// 打开数据库
	async openDB() {
		return new Promise((resolve, reject) => {
			plus.sqlite.openDatabase({
				name: this.name,
				path: this.path,
				success: function(e) {
					console.log('openDatabase success!');
					resolve(e)
				},
				fail: function(e) {
					console.error('openDatabase failed: ' + JSON.stringify(e));
				}
			});
		}).then(function(e) {
			return e;
		});
	}
	//判断数据库是否打开
	isOpen() {
		return plus.sqlite.isOpenDatabase({
			name: this.name,
			path: this.path
		});
	}
	//关闭数据库
	close(callbackFunction) {
		plus.sqlite.closeDatabase({
			name: this.name,
			success: function(e) {
				console.log('closeDatabase success!');
				if (typeof callbackFunction === "function")
					callbackFunction();
			},
			fail: function(e) {
				console.error('closeDatabase failed: ' + JSON.stringify(e));
			}
		});
	}
	// 执行SQL语句
	executeSQL(sql, callbackFunction) {
		plus.sqlite.executeSql({
			name: this.name,
			sql: sql,
			success: function(e) {
				console.log(sql, 'executeSql success!');
				if (typeof callbackFunction === "function")
					callbackFunction();
			},
			fail: function(e) {
				console.error(sql, 'executeSql failed: ' + JSON.stringify(e));
			}
		});
	}
	// 查询SQL语句
	selectSQL(sql, callbackFunction) {
		plus.sqlite.selectSql({
			name: this.name,
			sql: sql,
			success: function(data) {
				console.log(sql, 'selectSql success: ');
				if (typeof callbackFunction === "function")
					callbackFunction(data);
			},
			fail: function(e) {
				console.error(sql, 'selectSql failed: ' + JSON.stringify(e));
			}
		});
	}
	async selectSQLSync(sql) {
		return new Promise((resolve, reject) => {
			plus.sqlite.selectSql({
				name: this.name,
				sql: sql,
				success: function(data) {
					console.log(sql, 'selectSql success: ');
					resolve(data); //等待异步方法执行完 执行then
				},
				fail: function(e) {
					console.error(sql, 'selectSql failed: ' + JSON.stringify(e));
				}
			});
		}).then(function(data) {
			return data;
		});
	}
}
export default DB
